package com.pxmeta.common.utils.auth;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.pxmeta.common.constant.HttpStatus;
import com.pxmeta.common.exception.ServiceException;
import com.pxmeta.common.utils.HttpUtils;
import lombok.SneakyThrows;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.util.*;

@Component
public class YunDunClient {


    @Value("${yundun.secretId}")
    private String secretId;

    @Value("${yundun.secretKey}")
    private String secretKey;

    @Value("${yundun.businessId}")
    private String businessId;

    //发送通知类和运营类短信的请求路径URL
    private static final String
            SERVER_URL="https://api.netease.im/sms/sendtemplate.action";
    //网易云信分配的账号，请替换你在管理后台应用下申请的Appkey
    private static final String
            APP_KEY="cba8047edc94ea7a2df1ddb6e97e2536";
    //网易云信分配的密钥，请替换你在管理后台应用下申请的appSecret
    private static final String APP_SECRET="60db799cde5a";
    //随机数
    private static final String NONCE="123456";
    //短信模板ID
    private static final String TEMPLATEID="22522256";

    @SneakyThrows
    public static void sendNotice(String phone,String nickname, String targetNickname) {
        phone = "['"+phone+"']";
        String params = "['"+nickname+"','"+targetNickname+"']";

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(SERVER_URL);
        String curTime = String.valueOf((new Date()).getTime() / 1000L);
        /*
         * 参考计算CheckSum的java代码，在上述文档的参数列表中，有CheckSum的计算文档示例
         */
        String checkSum = CheckSumBuilder.getCheckSum(APP_SECRET, NONCE, curTime);

        // 设置请求的header
        httpPost.addHeader("AppKey", APP_KEY);
        httpPost.addHeader("Nonce", NONCE);
        httpPost.addHeader("CurTime", curTime);
        httpPost.addHeader("CheckSum", checkSum);
        httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");

        // 设置请求的的参数，requestBody参数
        List<NameValuePair> nvps = new ArrayList<>();
        /*
         * 1.如果是模板短信，请注意参数mobile是有s的，详细参数配置请参考“发送模板短信文档”
         * 2.参数格式是jsonArray的格式，例如 "['13888888888','13666666666']"
         * 3.params是根据你模板里面有几个参数，那里面的参数也是jsonArray格式
         */
        nvps.add(new BasicNameValuePair("templateid", TEMPLATEID));
        nvps.add(new BasicNameValuePair("mobiles", phone));
        nvps.add(new BasicNameValuePair("params", params));

        httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));

        // 执行请求
        HttpResponse response = httpClient.execute(httpPost);
        /*
         * 1.打印执行结果，打印结果一般会200、315、403、404、413、414、500
         * 2.具体的code有问题的可以参考官网的Code状态表
         */
        System.out.println(EntityUtils.toString(response.getEntity(), "utf-8"));

    }




    @SneakyThrows
    public String checkGetPhone(String token, String accessToken){
        String API_URL = "https://ye.dun.163yun.com/v1/oneclick/check";
        Map<String, String> body = this.getCommonParam();
        // 2.设置私有属性
        body.put("accessToken", accessToken); // 运营商预取号获取到的token
        body.put("token", token); // c
        // accessToken, token都是一次性有效, 且2分钟后自动过期
        // 3.生成签名信息
        String signature = SignatureUtils.genSignature(secretKey, body);
        body.put("signature", signature);
        JSONObject jsonObject = HttpUtils.doPostForm(API_URL, body);
        Integer code = jsonObject.getInteger("code");
        if (code == 200){
            JSONObject data = jsonObject.getJSONObject("data");
            String phone = data.getString("phone");
            if (StringUtils.isNotEmpty(phone)) {
                // 取号成功, 成功登录系统
                return phone;
            } else {
                String resultCode = data.getString("resultCode");
                // 降级走短信
                throw new ServiceException("号码一键登录获取号码失败! 错误码："+resultCode,HttpStatus.PARAMS_ERROR);
            }
        }else {
            throw new ServiceException("云盾调用失败! 错误码："+code,+HttpStatus.PARAMS_ERROR);
        }
    }





    private Map<String,String> getCommonParam(){
        Map<String, String> body = Maps.newHashMap();
        // 1.设置公共参数
        body.put("secretId", secretId);
        body.put("businessId", businessId);
        body.put("version", "v1");
        body.put("timestamp", String.valueOf(System.currentTimeMillis())); // 格式为时间戳格式, 与当前时间差值不能超过6s
        body.put("nonce", UUID.randomUUID().toString().replace("-", "")); // 32随机字符串

        return body;
    }




}
